package server;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private ServerSocket serverSocket;
    private Map<String, HttpServlet> servletMap;

    public RequestProcessor(ServerSocket serverSocket, Map<String, HttpServlet> servletMap) {
        this.serverSocket = serverSocket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {

        while (true){
            try {
                Socket socket = serverSocket.accept();

                InputStream inputStream = socket.getInputStream();

                // 封装Request对象和Response对象
                Request request = new Request(inputStream);
                Response response = new Response(socket.getOutputStream());

                // 静态资源处理
                if (servletMap.get(request.getUrl()) == null) {
                    response.outputHtml(request.getUrl());
                } else {
                    System.out.println("url=====+++" + request.getUrl());
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request, response);
                }

                socket.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
